use axum::Router;
mod bootstrap;
mod controller;
mod router;
mod webauth;

use crate::bootstrap::{AppState, init_logging, run_server};
use tracing::{error, info};

use tower_sessions::{
    Expiry, MemoryStore, SessionManagerLayer,
    cookie::{SameSite, time::Duration},
};

#[tokio::main]
async fn main() {
    if std::env::var_os("RUST_LOG").is_none() {
        unsafe {
            std::env::set_var("RUST_LOG", "webauthn_back=debug");
        }
    }

    let _ = dotenv::dotenv().ok();

    init_logging();

    let config = match crate::bootstrap::config::Configuration::from_env().await {
        Ok(c) => c,
        Err(e) => panic!("配置文件读取失败 : {}", e.to_string()),
    };

    let state = AppState::new();

    let session_store = MemoryStore::default();

    let app: Router = crate::router::create_routes()
        .await
        .with_state(state)
        .layer(
            SessionManagerLayer::new(session_store)
                .with_name("webauthnrs")
                .with_same_site(SameSite::Strict)
                .with_secure(false)
                .with_expiry(Expiry::OnInactivity(Duration::seconds(360))),
        );

    let bind_listener = config.get_bind_listener();

    match run_server(app, bind_listener).await {
        Ok(_) => info!("服务正常终止"),
        Err(e) => {
            error!(error = %e, "💥 服务启动失败");
            std::process::exit(1);
        }
    }
}
